<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;

class StickyTopic extends Model
{
    use SoftDeletes;

    const POSITION_INDEX = 1;

    const POSITION_FORUM = 2;

    public static $positionText = [
        self::POSITION_INDEX => '首页',
        self::POSITION_FORUM => '所在版块',
    ];

    protected $table = 'sticky_topics';

    protected $fillable = [
        'tid',
        'position',
        'display_order',
    ];

    public static function booted()
    {
        static::created(function (Model $model) {
            $topic = $model->topic;
            $operateLog = [
                'type' => TopicOperationLog::TYPE_SET_STICKY,
                'remarks' => sprintf('设置置顶'),
                'extra' => ['stick_info' => $model->toArray()]
            ];
            $operateLog = $topic->operationLogs()->create($operateLog);
            $log = sprintf(
                '%s, 设置置顶, operationLog: %s',
                __METHOD__, $operateLog->id
            );
            logger($log);
        });

        static::deleted(function (Model $model) {
            $topic = $model->topic;
            $operateLog = [
                'type' => TopicOperationLog::TYPE_CANCEL_STICKY,
                'remarks' => sprintf('取消置顶'),
                'extra' => ['stick_info' => $model->toArray()]
            ];
            $operateLog = $topic->operationLogs()->create($operateLog);
            $log = sprintf(
                '%s, 取消置顶, operationLog: %s',
                __METHOD__, $operateLog->id
            );
            logger($log);
        });
    }

    public function getPositionAttribute($value)
    {
        if (!is_array($value)) {
            return explode(',', $value);
        }
    }

    public function setPositionAttribute($value)
    {
        if (is_array($value)) {
            $this->attributes['position'] = implode(',', $value);
        }

    }

    public function getPositionTextAttribute()
    {
        $result = [];
        foreach ($this->position as $item) {
            $result[] = self::$positionText[$item] ?? '';
        }
        return implode(', ', array_filter($result));
    }

    public function scopePositionIndex(Builder $query)
    {
        $query->whereRaw(sprintf("find_in_set('%s', `position`)", self::POSITION_INDEX));
    }

    public function scopePositionForum(Builder $query)
    {
        $query->whereRaw(sprintf("find_in_set('%s', `position`)", self::POSITION_FORUM));
    }

    public function topic()
    {
        return $this->belongsTo(Topic::class, 'tid', 'id');
    }
}
